﻿using System;
using System.Windows.Forms;

namespace IchiaTester
{
    /// <summary>
    /// 用户管理窗体
    /// </summary>
    public partial class UserForm : Form
    {
        private int selectUser = -1; //-1 is not select 默认不选中任何用户
        private MainForm mainForm; // 在主窗体启动

        public UserForm(MainForm form)
        {
            mainForm = form;
            InitializeComponent();
        }

        /// <summary>
        /// 用户管理窗体创建前触发事件
        /// Load事件是在窗体第一次显示之前触发的，通常用于初始化控件、加载数据或者设置窗体属性的地方
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserForm_Load(object sender, EventArgs e)
        {
            MainForm.InfoLogAppend("Try to load User Form", MainForm.SystemState.AppSetting);

            // 初始化用户数量为0
            int userCount = 0;
            // 拼接用户配置文件路径 - 以文件的形式存储用户,持久化到磁盘
            SystemSetting.userInfoPath = Application.StartupPath + "\\" + SystemSetting.USER_INFO_FILENAME;
            MainForm.InfoLogAppend($"Try to load user info file: {SystemSetting.userInfoPath}",
                MainForm.SystemState.FileLoading);
            try
            {
                foreach (string userName in SystemSetting.UserInfoDict.Keys)
                {
                    // 创建ListViewItem
                    ListViewItem item = new ListViewItem(userCount.ToString());
                    item.SubItems.Add(SystemSetting.UserInfoDict[userName].FactoryName); // 工厂名
                    item.SubItems.Add(userName); // 用户名
                    item.SubItems.Add(SystemSetting.UserInfoDict[userName].Permission); // 权限
                    userlistView.Items.Add(item);
                }

                MainForm.InfoLogAppend($"Load user info file success: {SystemSetting.userInfoPath}",
                    MainForm.SystemState.LoadFileSuccess);
            }
            catch (Exception ex)
            {
                MainForm.ErrorLogAppend($"Error while loading user info file: {SystemSetting.userInfoPath}",
                    ex.Message + ex.StackTrace, MainForm.SystemState.ErrorHandling);
            }

            //is Admin Admin/工程师用户可以删除其他用户
            btnDeleteUser.Enabled = (SystemSetting.isAdmin || SystemSetting.isEngineer) ? true : false;
        }

        /// <summary>
        /// 窗体即将关闭时触发
        /// 数据保存,数据保存提示
        ///
        /// databaseConnection?.Close(); // 关闭数据库连接
        /// fileStream?.Dispose();       // 释放文件流
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DataManager.SaveUserFile(SystemSetting.userInfoPath);
        }

        /// <summary>
        /// 点击"添加"按钮,触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            // 创建编辑用户窗体
            UserEditForm userEditForm = new UserEditForm(this);
            userEditForm.isAdd = true;
            userEditForm.ShowDialog();
        }

        /// <summary>
        /// 点击"修改"按钮,触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEditUser_Click(object sender, EventArgs e)
        {
            if (userlistView.SelectedItems.Count > 0)
            {
                UserEditForm userEditForm = new UserEditForm(this);
                userEditForm.isAdd = false;

                //把選擇的內容帶入 userEditForm 打开新模态框前传值
                ListViewItem item = userlistView.SelectedItems[0]; // 当前选中的用户的信息
                userEditForm.tbFactory.Text = item.SubItems[1].Text; // 顯示選擇的項目的第一個子項
                userEditForm.tbUserName.Text = item.SubItems[2].Text;

                // 判断需要修改的用户的权限
                switch (item.SubItems[3].Text)
                {
                    case "User":
                        userEditForm.ShowDialog();
                        break;
                    case "Engineer":
                        if (!SystemSetting.isEngineer && SystemSetting.isAdmin)
                        {
                            MessageBox.Show("沒有權限修改Engineer用戶!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            userEditForm.ShowDialog();
                        }

                        break;
                    case "Admin":
                        if (!SystemSetting.isAdmin)
                        {
                            MessageBox.Show("沒有權限修改Admin用戶!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            userEditForm.ShowDialog();
                        }

                        break;
                }
            }
            else
            {
                MessageBox.Show("沒有選擇用戶!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 点击"删除"按钮,触发事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            try
            {
                if (userlistView.SelectedItems.Count <= 0)
                {
                    MessageBox.Show("沒有選擇用戶!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //is Admin
                    if (SystemSetting.isAdmin)
                    {
                        MessageBox.Show("Admin權限才可以進行刪除!!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        //刪除字典項目 在字典 内存中删除选中的用户
                        string userName = userlistView.SelectedItems[0].SubItems[2].Text;
                        SystemSetting.UserInfoDict.Remove(userName);

                        //delete item in listview 在显示框 listview 删除选中的用户
                        userlistView.Items.RemoveAt(userlistView.SelectedIndices[0]);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        /// <summary>
        /// ListView控件选中项发生改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void userlistView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (userlistView.SelectedItems.Count > 0)
            {
                selectUser = userlistView.SelectedItems[0].Index;
            }
        }

        /// <summary>
        /// 获取被选中的用户的索引
        /// </summary>
        /// <returns></returns>
        public int GetSelectIndex()
        {
            return selectUser;
        }
    }
}